package org.redmagic.ui;

import java.util.List;

import org.redmagic.api.HistoryDao;
import org.redmagic.api.PropertyDao;
import org.redmagic.api.UiService;
import org.redmagic.domain.InternalServiceProperty;
import org.redmagic.domain.Tags;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.common.collect.Lists;

@Service
public class UiServiceImpl implements UiService {

	private static final Logger LOGGER = LoggerFactory
			.getLogger(UiServiceImpl.class);

	private final PropertyDao propertyDao;

	// private final HistoryDao historyDao;

	@Autowired
	public UiServiceImpl(PropertyDao propertyDao, HistoryDao historyDao) {
		this.propertyDao = propertyDao;
		// this.historyDao = historyDao;
	}

	@Override
	public Tags getAllTags() {
		return new Tags(propertyDao.getAllTags());
	}

	@Override
	public Tags getSelectedTags(String key) {
		return new Tags(propertyDao.getSelectedTags(key));
	}

	@Override
	public long getPropertyCount() {
		return propertyDao.getPropertyCount();
	}

	@Override
	public List<UiProperty> listProperties() {
		LOGGER.info("Getting all properties");
		List<InternalServiceProperty> properties = propertyDao
				.getAllProperties();
		List<UiProperty> tableProperties = getTableProperties(properties);
		LOGGER.info("Found {} properties", tableProperties.size());
		return tableProperties;
	}

	@Override
	public List<UiProperty> listProperties(int startIndex, int pageSize) {
		LOGGER.info("Getting all properties");
		List<InternalServiceProperty> properties = propertyDao
				.getAllProperties();
		List<UiProperty> tableProperties = getTableProperties(properties);
		LOGGER.info("Found {} properties", tableProperties.size());
		return tableProperties;
	}

	private List<UiProperty> getTableProperties(
			List<InternalServiceProperty> properties) {
		List<UiProperty> tableProperties = Lists
				.newArrayListWithExpectedSize(properties.size());
		for (InternalServiceProperty property : properties) {
			tableProperties.add(UiProperty.fromUiProperty(property));
		}
		return tableProperties;
	}

	@Override
	public void createProperty(UiProperty property) {
		propertyDao.createProperty(property.getName(), property.getTags(),
				property.getValue(), property.getGroup());
	}

	@Override
	public void updateProperty(UiProperty property) {
		propertyDao.updateProperty(property.getKey(), property.getName(),
				property.getTags(), property.getValue(), property.getGroup());
	}

	@Override
	public void removeProperty(String key) {
		propertyDao.removeProperty(key);
	}

}
